Categories
React Tips

React Tips — Formik Blur, Router Navigation, Context Value

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Ternary Operator in JSX to Include HTML

We can add the ternary operator to include HTML by writing the following

render () {
  return (
    <div>
      {(this.state.message === 'success')
          ? <div>successful</div>
          : <div>not successful</div>
      }
    </div>
  );
}

Change Context Value While Using React Hook of useContext

We can pass in the state change function to the context to let us call them anywhere.

This way, we can change the value in whatever component that receives the context.

For example, we can write:

const { createContext, useContext, useState } = React;

const ThemeContext = createContext({});

function Content() {
  const { style, color, toggleStyle, changeColor } = useContext(
    ThemeContext
  );

  return (
    <div>
      <p>
        {color} {style}
      </p>
      <button onClick={toggleStyle}>Change style</button>
      <button onClick={() => changeColor('green')}>Change color</button>
    </div>
  );
}

function App() {
  const [style, setStyle] = useState("light");
  const [color, setColor] = useState(true);

  function toggleStyle() {
    setStyle(style => (style === "light" ? "dark" : "light"));
  }

  function changeColor(color) {
    setColor(color);
  }

  return (
    <ThemeContext.Provider
      value={{ style, visible, toggleStyle, changeColor }}
    >
      <Content />
    </ThemeContext.Provider>
  );
}

We created the ThemeContext , which we use in the App component to get the provider and wrap that around the Content component.

Then we pass our state change functions with the state variables into the context by passing them into the object in the value prop.

Then in the Content component, we can call the toggleStyle and toggleStyle and changeColor functions to change the states in App .

We get those functions in Content with the useContext hook.

Simulate a Change Event with Enzyme

We can simulate a change event with Enzyme by creating a spy for the handle change method.

For instance, we can write:

it("responds to name change", done => {
  const handleChangeSpy = sinon.spy(Form.prototype, "handleChange");
  const event = { target: { name: "name", value: "spam" }};
  const wrap = mount(
    <Form />
  );
  wrap.ref('name').simulate('change', event);
  expect(handleChangeSpy.calledOnce).to.equal(true);
})

We create a spy for our change event listener.

Then we set our event object.

And then we mount our Form component that we want to test.

And then we trigger the change event on it with the simulate method.

Then we checked that the spy is called once.

How to Use Custom onChange and onBlur with React Formik

We can create our own blur handler by writing:

<Field
    component={MyInput}
    name="email"
    type="email"
    onBlur={e => {
        handleBlur(e)
        let someValue = e.currentTarget.value
        //...
    }}
/>

We call the built-in handleBlur function.

Then we do something else in the lines after.

How to Use React Router with Electron

We can use React Router in an Electron app with the HashRouter ,

For instance, we can write:

<HashRouter
  basename={basename}
  getUserConfirmation={() => {}}
  hashType='slash'
>
  <App />
</HashRouter>

basename is a string with the base URL for all locations.

getUserConfirmation is a function that lets us use to confirm navigation.

hashType is a string that has the encoding to use for window.location.hash .

The possible values are 'slash' , which is #/ .

'noslash' is # .

And 'hashbang' us #!/ .

Cannot Read Property ‘push’ of undefined With React Router

We can use the withRouter higher-order component to make the history object available.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(value) {
    this.props.history.push('/dashboard');
  }

  render() {
    return (
      <div>
        <Route
          exact
          path="/"
          render={() => (
            <div>
              <h1>Welcome</h1>
            </div>
          )}
       />
       <Route
         path="/dashboard"
         render={() => (
           <div>
             <h1>Dashboard</h1>
           </div>
         )}
      />
      <button onClick={this.handleClick} >go to dashboard</button>
    );
  }
}

export default withRouter(App);

We have several routes and a handleClick method to let us go to the dashboard route.

We have the this.props.history.push method because we called withRouter higher-order component with App .

Conclusion

We can navigate to routes programmatically with withRouter .

We can pass anything to a context so that we can use them anywhere else.

Formik’s blur handler can be replaced with our own function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *